﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace SerialPortTest
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {

        private CommunicationLib.Serial.COM32 com = new CommunicationLib.Serial.COM32();

        public MainWindow()
        {
            InitializeComponent();
            this.Closing += new System.ComponentModel.CancelEventHandler(MainWindow_Closing);
            Cmb_Check.ItemsSource =Enum.GetNames(typeof(System.IO.Ports.Parity));
            Cmb_StopBit.ItemsSource = Enum.GetNames(typeof(System.IO.Ports.StopBits));
            Cmb_PortNum.ItemsSource = CommunicationLib.Serial.COM32.ComList();
        }

        void MainWindow_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            com.ClosePort();
        }

        private void Btn_OpenOrClose_Click(object sender, RoutedEventArgs e)
        {
            if (Btn_OpenOrClose.Content.Equals("关闭串口"))
            {
                Btn_OpenOrClose.Content = "打开串口";
                com.ClosePort();
                return;
            }

            try
            {
                com.BaudRate = int.Parse(Cmb_BaudRate.Text);
                com.DataBits = int.Parse(Cmb_Bit.Text);
                com.StopBit = (System.IO.Ports.StopBits)Enum.Parse(typeof(System.IO.Ports.StopBits), Cmb_StopBit.Text);
                com.CheckBits = (System.IO.Ports.Parity)Enum.Parse(typeof(System.IO.Ports.Parity), Cmb_Check.Text);

                com.PortNum = Cmb_PortNum.Text;

                com.IsHalfDuplex = false;

                com.TimeOut = 1000;

                com.ByteTimeOut = 500;

                com.OpenPort();

                if (!com.BeginListening(new CommunicationLib.Serial.COM32.AsyncSerailCallback((byts) =>
                                                                            this.Dispatcher.BeginInvoke(new Action(() =>
                                                                                                     {
                                                                                                         FlowDocument doc = RichTxt_Data.Document;

                                                                                                         Paragraph p = new Paragraph();

                                                                                                         Run r = new Run(BitConverter.ToString(byts).Replace("-", ""));

                                                                                                         r.Foreground = Brushes.DarkRed;

                                                                                                         p.Inlines.Add(r);

                                                                                                         doc.Blocks.Add(p);

                                                                                                     }
                                                                                                 ))))) return;

                Btn_OpenOrClose.Content = "关闭串口";
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return;
            }
        }

        private void Btn_Clear_Click(object sender, RoutedEventArgs e)
        {
            RichTxt_Data.Document.Blocks.Clear();
        }

        private void Btn_Send_Click(object sender, RoutedEventArgs e)
        {
            byte[] bytSends;

            if ((bool)Chk_Hex.IsChecked)
            {
                string sendString = Txt_SendData.Text.Trim().Replace(" ", "");

                if (sendString.Length % 2 != 0) 
                {
                    MessageBox.Show("数据格式不正确...");
                    return;
                }

                 bytSends= new byte[sendString.Length / 2];

                for (int i = 0; i < bytSends.Length; i++)
                {
                    bytSends[i] = byte.Parse(sendString.Substring(i * 2, 2), System.Globalization.NumberStyles.AllowHexSpecifier);
                }
            }
            else
            {
                string sendString = Txt_SendData.Text;
                bytSends = ASCIIEncoding.ASCII.GetBytes(sendString);
            }

            com.IsHalfDuplex=(bool)Chk_HalfDuplex.IsChecked;
            try
            {
                com.BeginSendData(bytSends);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
    }
}
